package com.ivr.cm.handler.validate.impl;

import java.text.SimpleDateFormat;
import java.util.AbstractMap;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

import com.ivr.cm.cache.Cacheable;
import com.ivr.cm.dao.ILimitCodeDao;
import com.ivr.cm.data.ValidateData;
import com.ivr.cm.handler.validate.ValidateServiceIF;
import com.ivr.cm.service.StateCode;
import com.ivr.cm.vo.LimitCodeVo;

/**
 * 业务总量 鉴权
 * @author liugeng
 * @date 2015-12-15
 *
 */
public class ValidateLimitCodeImpl implements ValidateServiceIF {
	private static Logger logger = Logger.getLogger(ValidateLimitCodeImpl.class);
	
	private Cacheable limitCodeCache;
	private ILimitCodeDao limitCodeDao;
	private int threshold = new Random().nextInt(200);
	
	@Override
	public int doProcess(ValidateData validateData) {
		/**获得主叫号码*/
		String mobile = validateData.getBaseData().getCalling();
		/**获得业务号码长号码*/
		String sp_number = validateData.getBaseData().getLong_called();
		/**获得业务号码短号码*/
		String sp_code= validateData.getBaseData().getShort_called();
		
		logger.info(String.format("[%s][%s][业务总量限制鉴权]开始", mobile, sp_number));
		
		AbstractMap<String, List<LimitCodeVo>> limitCodeMap = (AbstractMap<String, List<LimitCodeVo>>) limitCodeCache.getCache();
		
		boolean flag = false;
		if(limitCodeMap != null && limitCodeMap.size() > 0){
			/**根据业务长号码获得对应的渠道信息*/
			int sp_code_id = limitCodeDao.getSpCodeIdBySpCode(sp_code);
			if(sp_code_id != 0){
				List<LimitCodeVo> limitCodeVoList = limitCodeMap.get(String.valueOf(sp_code_id));
				
				if(limitCodeVoList != null && limitCodeVoList.size() > 0){
					boolean isExists = false;
					for(LimitCodeVo limitCodeVo : limitCodeVoList){
						if("".equals(limitCodeVo.getProvince()) || validateData.getBaseData().getProvince().equals(limitCodeVo.getProvince())){
							isExists = true;
							/**格式化业务总量限制的当天和当月*/
							Date nowDate = new Date();
							SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd");
							String day_time = formatDay.format(nowDate);
							SimpleDateFormat formatMonth = new SimpleDateFormat("yyyy-MM");
							String month_time = formatMonth.format(nowDate);
							
							/** 根据省份信息查询所有短号码在当日已经拨打金额 */
							String currProvince = validateData.getBaseData().getProvince();
							int max_Province_fee = 9500 + this.threshold;
							logger.info(String.format("[全业务总量限制鉴权随机值为]:[%d]", max_Province_fee));
							if(currProvince.equals("江苏") || currProvince.equals("四川")) {
								int totalused_day = limitCodeDao.getTotalUsedDay(currProvince, day_time);
								if(totalused_day >= max_Province_fee ){
									logger.info(String.format("[%s][%s][全业务总量限制鉴权]未通过, 配置省[%s], 日限金额[%d] 当天已用金额[%d]", mobile, sp_number, currProvince, max_Province_fee, totalused_day));
									flag = true;
									break;
								}
							}
							
							/**根据业务ID和省份获得短号码在当前省份当日已经拨打金额*/
							int lowerused_day = limitCodeDao.getSpCodeUsedDay(sp_code, validateData.getBaseData().getProvince(), day_time);
							if(lowerused_day >= limitCodeVo.getDay_limit()){
								logger.info(String.format("[%s][%s][业务总量限制鉴权]未通过,渠道[lower_id=%d], 配置省[%s], 日限金额[%d] 当天已用金额[%d]", mobile, sp_number, sp_code, limitCodeVo.getProvince(), limitCodeVo.getDay_limit(), lowerused_day));
								flag = true;
								break;
							}
							
							/**根据业务ID和省份获得短号码在当前省份当月已经拨打金额*/
							int lowerused_month = limitCodeDao.getSpCodeUsedMonth(sp_code, validateData.getBaseData().getProvince(), month_time);
							if(lowerused_month >= limitCodeVo.getMonth_limit()){
								logger.info(String.format("[%s][%s][业务总量限制鉴权]未通过,渠道[lower_id=%d], 配置省[%s], 月限金额[%d] 当月已用金额[%d]", mobile, sp_number, sp_code, limitCodeVo.getProvince(), limitCodeVo.getMonth_limit(), lowerused_month));
								flag = true;
								break;
							}
							
							logger.info(String.format("[%s][%s]短号码[%s][业务总量限制鉴权]通过, 配置省[%s], 日限金额[%d], 月限金额[%d], 当天已用金额[%d], 当月已用金额[%d]", mobile, sp_number, sp_code, validateData.getBaseData().getProvince(),limitCodeVo.getDay_limit(),limitCodeVo.getMonth_limit(),lowerused_day,lowerused_month));
							
						}
					}
					if(!isExists){
						logger.info(String.format("[%s][%s]短号码[%s][业务总量限制鉴权]通过,无[%s]省份限制", mobile, sp_number, sp_code, validateData.getBaseData().getProvince()));
					}
				}else{
					logger.info(String.format("[%s][%s]短号码[%s][业务总量限制鉴权]通过,无业务限制配置信息", mobile, sp_number, sp_code));
				}
			}else{
				logger.info(String.format("[%s][%s]短号码[%s][业务总量限制鉴权]通过,无短号码限配置信息", mobile, sp_number,sp_code));
			}
		}else{
			logger.info(String.format("[%s][%s]短号码[%s][业务总量限制鉴权]通过,无短号码限制配置信息", mobile, sp_number, sp_code));
		}
		
		if(flag){
			validateData.setResult(ValidateData.RESULT_INVALID_NOTIMELEFT);
			validateData.setVoice(ValidateData.VOICE_INVALID_NOTIMELEFT);
			validateData.setTimeRemain(0);
			validateData.setStatecode(StateCode.SP_CODE_CONFIG_LIMIT);
			return ValidateChain.VALIDATE_FINISHED;
		}
		
		return ValidateChain.VALIDATE_CONTINUE;
	}

	public Cacheable getLimitCodeCache() {
		return limitCodeCache;
	}

	public void setLimitCodeCache(Cacheable limitCodeCache) {
		this.limitCodeCache = limitCodeCache;
	}

	public ILimitCodeDao getLimitCodeDao() {
		return limitCodeDao;
	}

	public void setLimitCodeDao(ILimitCodeDao limitCodeDao) {
		this.limitCodeDao = limitCodeDao;
	}
}